import { makeAutoObservable, runInAction } from 'mobx'
import type { FormIDataItem } from './interface'
import { history } from 'umi'
import { getData, postData } from '@/servers/http'
import { api } from '@/servers/api'
import { getLocalStorage, setLocalStorage } from '@/storage'
import { dataURLtoFile, isNullData } from '@/utils'
import { uploadFile } from '../careerrainbow/api'
class Store {
    isFinished: boolean = false
    step: number = 1
    stepData: FormIDataItem[] = []
    barriersInfo: any = []
    /** 是否编辑过 */
    isEdit: boolean = false

    constructor() {
        makeAutoObservable(this)
    }
    setIsEdit = (data: boolean) => {
        this.isEdit = data || false
    }
    /** 获取生涯彩虹图草稿详情 */
    getDraftInfo = () => {
        getData(api.rainbowDraftInfo).then(({ data }) => {
            const dealData = data.map((item: any, index: any) => {
                const settings = item.settings
                    ? item.settings?.map((i: any, idx: any) => {
                          return {
                              ...i,
                              sort: idx + 1,
                              age_start: [i.age_start],
                              age_end: [i.age_end],
                              // 投入程度改为最大是3
                              grade: Number(i.grade) > 3 ? 3 : Number(i.grade),
                          }
                      })
                    : [{ grade: '1' }]
                return {
                    ...item,
                    sort: index + 1,
                    age_start: [item.age_start],
                    age_end: [item.age_end],
                    settings,
                }
            })
            this.stepData = dealData
            this.barriersInfo = data
        })
    }
    /** 获取生涯彩虹图详情 */
    getRainbowDetail = (callback: (arg0: any) => void) => {
        getData(api.rainbowRoles).then(({ status, data }) => {
            if (status === 200 && data) {
                callback?.(data)
                const dealData = data.map((item: any, index: any) => {
                    const settings = item.settings?.map((i: any, idx: any) => {
                        return {
                            ...i,
                            sort: idx + 1,
                            age_start: [i.age_start],
                            age_end: [i.age_end],
                            // 投入程度改为最大是3
                            grade: Number(i.grade) > 3 ? 3 : Number(i.grade),
                        }
                    })
                    return {
                        ...item,
                        sort: index + 1,
                        age_start: [item.age_start],
                        age_end: [item.age_end],
                        settings,
                    }
                })
                this.stepData = dealData
                this.barriersInfo = data
                if (isNullData(data)) {
                    this.getDraftInfo()
                }
            }
        })
    }
    /** 保存彩虹图草稿 */
    saveDraft = () => {
        const data = this.stepData.map((item, index) => {
            return {
                sort: index + 1,
                name: item.name,
                age_start: item.age_start[0],
                age_end: item.age_end[0],
            }
        })
        postData(api.rainbowDraft, { data })
    }
    /** 下一步 */
    nextStep = ({ data }: { data: FormIDataItem[] }) => {
        const { id } = history.location.query || {}
        runInAction(() => {
            /** 保存数据 */
            this.stepData = data.map(item => ({
                ...item,
                settings: item.settings ? item.settings : [{ grade: '1' }],
            }))
            this.saveDraft()
            history.replace(`/rainbow/step2/${id}?id=${id}`)
        })
    }

    /** 生成彩虹图 */
    submit = ({ data }: { data: FormIDataItem[] }, generateRef: any) => {
        const { id } = history.location.query || {}
        const dealData = data.map((item, index) => {
            const settings = item.settings?.map((i, idx) => {
                return {
                    ...i,
                    sort: idx + 1,
                    age_start: i.age_start?.[0],
                    age_end: i.age_end?.[0],
                }
            })
            return {
                ...item,
                sort: index + 1,
                age_start: item.age_start?.[0],
                age_end: item.age_end?.[0],
                settings,
            }
        })
        const base64Str = generateRef.current?.exportImage(JSON.parse(JSON.stringify(dealData)))
        if (base64Str) {
            const file = dataURLtoFile(base64Str, 'rainbow' + Math.floor(Math.random() * 10) + new Date().getTime() + '.png')
            uploadFile(file).then(result => {
                postData(api.rainbowRoles, { data: dealData, url: result.data.url }).then(res => {
                    this.isEdit = true
                    this.isFinished = res.data?.is_first_view === '1' ? false : true
                    this.barriersInfo = dealData
                    history.replace(`/rainbow/result/${id}?id=${id}` + (res.data.gain_medal ? `&medalData=${encodeURIComponent(JSON.stringify(res.data.gain_medal))}` : ``))
                    this.stepData = data
                })
            })
        }
    }
}

export default (() => {
    let store: any

    return function getStore() {
        if (store) {
            return store
        }
        store = new Store()
        return store
    }
})()
